<template>
  <div class="wangeditor">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <Editor
      style="height: 350px; overflow-y: hidden"
      v-model="modelValue"
      :defaultConfig="editorConfig"
      mode="default"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { shallowRef, ref, onMounted, toRefs, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
const toolbarConfig = ref({});
const props = defineProps({
  modelValue: String,
});
const { modelValue } = toRefs(props);
const editorConfig = {
  placeholder: "请输入内容...",
  autoFocus: true,
  MENU_CONF: {
    uploadImage: {
      maxFileSize: 1 * 1024 * 1024, // 1M
      maxNumberOfFiles: 10, // 最多可上传几个文件，默认为 100
      base64LimitSize: 5 * 1024, // 5kb 小于该值就插入 base64 格式（而不上传），默认为 0
      server: "htttp://localhost:4000/api/upload",
      onBeforeUpload(file) /*  上传之前触发 */ {
        // file 选中的文件，格式如 { key: file }
        return file;

        // 可以 return
        // 1. return file 或者 new 一个 file ，接下来将上传
        // 2. return false ，不上传这个 file
      },
      onProgress(progress) {
        // progress 是 0-100 的数字
        console.log("progress", progress);
      },
      onSuccess(file, res) {
        console.log(`${file.name} 上传成功`, res);
      },
      onFailed(file, res) {
        console.log(`${file.name} 上传失败`, res);
      },
      onError(file, err, res) {
        console.log(`${file.name} 上传出错`, err, res);
      },
    },
    uploadVideo: {
      server: "/api/upload",
      withCredentials: true, //跨域是否传递 cookie ，默认为 false
    },
  },
};
const handleChange = (editor) => {
  const html = editor.getHtml();
  //   proxy.$emit("html", html);
    proxy.$emit("update:modelValue", html);
  //   console.log("editor content", html);
  //   // 也可以同步到 <textarea>
};
// 只能使用shallowRef
const editorRef = shallowRef();
const handleCreated = (editor) => {
  console.log("editor", editor);
  editorRef.value = editor; // 记录 editor 实例，重要！
};
onMounted(() => handleCreated());
</script>

<style lang="scss" scoped>
.wangeditor {
  border: 1px solid #ccc;
}
</style>
